import AMapLoader from '@amap/amap-jsapi-loader'

let isMap
async function tryLoad() {
  return new Promise((resolve, reject) => {
    if (isMap) {
      resolve(isMap)
      return
    }
    window._AMapSecurityConfig = {
      serviceHost: 'https://gps.teredy.com/_AMapService'
      // securityJsCode: '23bd8098ebaee53fb609a5f27c41eef3'
    }
    AMapLoader.load({
      key: 'c958f207aab179795b9f33376cc17968',
      // key: 'keys',
      version: '2.0'
    })
      .then((AMap) => {
        // console.log('aaa', AMap)
        isMap = AMap
        resolve(isMap)
      })
      .catch((e) => {
        console.log('AMapLoader error', e)
        reject(e)
      })
  })
}
/**
 * 高德逆向编码
 */
export const gdMap = (e) => {
  return new Promise(async (resolve, reject) => {
    isMap.plugin('AMap.Geocoder', function () {
      let geocoder = new isMap.Geocoder()
      geocoder.getAddress(e, function (status, result) {
        if (status === 'complete' && result.info === 'OK') {
          resolve(result.regeocode.formattedAddress)
        } else {
          reject('获取详细地址失败')
        }
      })
    })
  })
}

/**
 * 高德地图正向编码
 */
export const gpsMap = (e) => {
  return new Promise(async (resolve, reject) => {
    isMap.plugin('AMap.PlaceSearch', function () {
      let geocoder = new isMap.PlaceSearch()
      geocoder.search(e, function (status, result) {
        if (status === 'complete') {
          if (result.info === 'TIP_CITIES') {
            let data = result.cityList
            let query = {
              type: 'city',
              list: data.slice(0, 100)
            }
            resolve(query)
          } else if (result.info === 'OK') {
            let data = result.poiList.pois
            let query = {
              type: 'address',
              list: data
            }
            resolve(query)
          }
        } else {
          reject('获取经纬度失败')
        }
      })
    })
  })
}

// 获取浏览器地理位置
export const browserLocal = () => {
  return new Promise((resolve, reject) => {
    tryLoad()
      .then((gAMap) => {
        // console.log('gAMap', gAMap)
        gAMap.plugin('AMap.Geolocation', () => {
          // console.log('gAMap11')
          let geolocation = new gAMap.Geolocation({
            // 高精度
            enableHighAccuracy: true,
            timeout: 10000,
            convert: false
          })
          geolocation.getCurrentPosition((status, result) => {
            console.log(status, result)
            if (status === 'complete') {
              let pos = {
                lat: result.position.lat,
                lng: result.position.lng
              }
              resolve(pos)
            } else {
              reject('定位失败，请稍后重试')
              // var citySearch = new gAMap.CitySearch() // 获取当前所在城市
              // citySearch.getLocalCity(function (status, result) {
              //   console.log('getLocalCity', status, result)
              //   if (status === 'complete' && result.info === 'OK') {
              //     var geocoder = new gAMap.Geocoder() //逆地理解析
              //     let provinceCity = result.province + result.city // 查询成功，result即为当前所在城市信息
              //     // 根据当前城市逆解析拿到经纬度
              //     geocoder.getLocation(provinceCity, function (status, result) {
              //       console.log('getLocation', status, result)
              //       if (status === 'complete' && result.info === 'OK') {
              //         let _location = result.geocodes[0].location
              //         longitude.value = _location.lng
              //         latitude.value = _location.lat
              //       }
              //     })
              //   }
              // })
            }
          })
          // gAMap.event.addListener(geolocation, 'complete', (d) => {
          //   console.log(d)
          // }) //返回定位信息
          // gAMap.event.addListener(geolocation, 'error', (e) => {
          //   console.log('error', e)
          // }) //返回定位出错信息
        })
      })
      .catch((e) => {
        reject(e)
      })
  })
}

// 获取行政区域
export const getDivision = (e, v) => {
  return new Promise((resolve, reject) => {
    isMap.plugin('AMap.DistrictSearch', function () {
      // 创建行政区查询对象
      let district = new isMap.DistrictSearch({
        // 返回行政坐标
        extensions: 'all',
        level: v
      })
      district.search(e, function (status, result) {
        if (result.info && result.info === 'OK') {
          let path = result.districtList[0].boundaries
          resolve(path)
        } else {
          reject('暂无该区域的边界坐标，地图无法加载')
        }
      })
    })
  })
}
// 驾车规划
export const getDriveRoute = (e, v) => {
  return new Promise((resolve, reject) => {
    // 公交路线规划（AMap.Transfer）
    // 步行路线规划（AMap.Walking）
    // 骑行路线规划（AMap.Riding）
    // 货车路线规划（AMap.TruckDriving）
    // 说明：货车路径规划为收费服务接口，目前提供免费配额每日调用次数上限100次，QPS上限1。如果您有更高配额要求或合作意向，请通过工单系统 提交商务合作工单 进行沟通。
    isMap.plugin('AMap.Driving', function () {
      var driving = new AMap.Driving({
        // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
        policy: AMap.DrivingPolicy.LEAST_TIME
      })

      var startLngLat = [116.379028, 39.865042]
      var endLngLat = [116.427281, 39.903719]

      driving.search(startLngLat, endLngLat, function (status, result) {
        // 未出错时，result即是对应的路线规划方案
        resolve(result)
      })
    })
  })
}
